package com.so206.controller;

import com.alibaba.fastjson.JSON;
import com.so206.plugins.FileManagerUpload;
import com.so206.plugins.MyCacheManager;
import com.so206.po.*;
import com.so206.po.ext.WXLoginRet;
import com.so206.service.*;
import com.so206.utils.HttpClientUtils;
import com.so206.utils.MailUtils;
import com.so206.utils.SMSUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 首页控制器
 */
@Controller
public class HomeController {

    @Autowired
    private MailUtils mailUtils;

    @Autowired
    private WebConfigService webConfigService;

    @Autowired
    private ApiDocService apiDocService;

    @Autowired
    private UserService userService;

    @Value("${spring.datasource.password}")
    private String key_pwd;

    @Autowired
    private FileManagerUpload manager;

    @Autowired
    private PayConfigService payConfigService;

    @Autowired
    private SMSConfig smsConfig;

    @Autowired
    private MyCacheManager myCacheManager;

    @Autowired
    private WxPayConfigService wxPayConfigService;

    @Autowired
    private MyCacheManager cacheManager;

    /**
     * 清空redis
     */
    @RequestMapping("/clear_cache")
    @ResponseBody
    public Map clear_redis(String key) {
        HashMap<Object, Object> map = new HashMap<>();
        if (key == null) {
            map.put("msg", "key error");
            map.put("code", 0);
            return map;
        }
        if (!key.equals(this.key_pwd)) {
            map.put("msg", "key error");
            map.put("code", 0);
            return map;
        }
        myCacheManager.removeAll();
        map.put("msg", "清理缓存OK");
        map.put("code", 0);
        return map;
    }

    /**
     * 首页
     */
    @RequestMapping("/")
    public String home(Model model) {
        SystemWeb web = webConfigService.find_by_id(1L);
        model.addAttribute("config", web);
        return "index";
    }

    /**
     * 开发文档
     */
    @RequestMapping("/doc.do")
    public String doc(Model model) {
        SystemWeb web = webConfigService.find_by_id(1L);
        List<SystemDoc> list = apiDocService.findAllDisplayDoc(1);
        model.addAttribute("config", web);
        model.addAttribute("api", list);
        return "doc";
    }

    /**
     * 微信扫码 - 绑定用户
     */
    @RequestMapping("/wxScanCode")
    public String wxScanCode(String auth) throws Exception {
        Object o = cacheManager.get("state:" + auth);
        Integer id = (Integer) o;
        if (id == null) {
            throw new Exception("用户识别失败!");
        }
        SystemPayConfig config = payConfigService.getPayConfig(1L);
        SystemWeb web = webConfigService.find_by_id(1L);
        WxpayConfig by_id = wxPayConfigService.find_by_id(config.getTrWxpay());
        String ret_url = URLEncoder.encode(web.getHttpUrl() + "/scancode/ret", "UTF-8");
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?";
        url += "appid=" + by_id.getAppId() + "&";
        url += "redirect_uri=" + ret_url + "&";
        url += "response_type=code&";
        url += "scope=snsapi_base&";
        url += "state=" + auth + "#wechat_redirect";
        cacheManager.remove("state:" + auth);
        cacheManager.set("state:" + auth, id, 120000);
        return "redirect:" + url;
    }

    /**
     * 微信 - 扫码绑定 - 回调
     */
    @RequestMapping("/scancode/ret")
    public String toWXScancode_ret(String code, String state, Model model) throws Exception {
        Object o = cacheManager.get("state:" + state);
        Long id = (Long) o;
        if (id == null) {
            throw new Exception("用户识别失败!");
        }
        String openid = null;
        SystemPayConfig config = payConfigService.getPayConfig(1L);
        WxpayConfig by_id = wxPayConfigService.find_by_id(config.getTrWxpay());
        if (code != null && state.length() > 0 && code.length() > 0) {
            String token_get_url = "https://api.weixin.qq.com/sns/oauth2/access_token";
            HashMap<String, String> param = new HashMap<>();
            param.put("appid", by_id.getAppId());
            param.put("secret", by_id.getPublicKeyGzh());
            param.put("code", code);
            param.put("grant_type", "authorization_code");
            String ret = HttpClientUtils.postParameters(token_get_url, param);
            WXLoginRet ret_model = JSON.parseObject(ret, WXLoginRet.class);
            if (ret_model.getOpenid() == null) {
                throw new Exception("信息错误,请返回重试!");
            }
            openid = ret_model.getOpenid();
        }
        SystemUser user = userService.findUserById(id);
        user.setZspaytype(1);
        user.setZspayid(openid);
        userService.updateUser(user);
        SystemUser user1 = userService.findUserById(user.getId());
        SystemWeb webConfigService_by_id = webConfigService.find_by_id(1L);
        model.addAttribute("config", webConfigService_by_id);
        model.addAttribute("user", user1);
        cacheManager.set("state_bind:" + state, 125, 120000);
        cacheManager.set("state_bind_openid:" + state, openid, 120000);
        return "bind_ok";
    }

    /**
     * 微信扫码 - 绑定用户
     */
    @RequestMapping("/wxScanCode2")
    public String wxScanCode2(String auth) throws Exception {
        SystemPayConfig config = payConfigService.getPayConfig(1L);
        SystemWeb web = webConfigService.find_by_id(1L);
        WxpayConfig by_id = wxPayConfigService.find_by_id(config.getTrWxpay());
        String ret_url = URLEncoder.encode(web.getHttpUrl() + "/scancode/ret2", "UTF-8");
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?";
        url += "appid=" + by_id.getAppId() + "&";
        url += "redirect_uri=" + ret_url + "&";
        url += "response_type=code&";
        url += "scope=snsapi_base&";
        url += "state=" + auth + "#wechat_redirect";
        return "redirect:" + url;
    }

    /**
     * 微信 - 扫码绑定 - 回调
     */
    @RequestMapping("/scancode/ret2")
    public String toWXScancode_ret2(String code, String state, Model model) throws Exception {
        String openid = null;
        SystemPayConfig config = payConfigService.getPayConfig(1L);
        WxpayConfig by_id = wxPayConfigService.find_by_id(config.getTrWxpay());
        if (code != null && state.length() > 0 && code.length() > 0) {
            String token_get_url = "https://api.weixin.qq.com/sns/oauth2/access_token";
            HashMap<String, String> param = new HashMap<>();
            param.put("appid", by_id.getAppId());
            param.put("secret", by_id.getPublicKeyGzh());
            param.put("code", code);
            param.put("grant_type", "authorization_code");
            String ret = HttpClientUtils.postParameters(token_get_url, param);
            WXLoginRet ret_model = JSON.parseObject(ret, WXLoginRet.class);
            if (ret_model.getOpenid() == null) {
                throw new Exception("信息错误,请返回重试!");
            }
            openid = ret_model.getOpenid();
        }
        SystemWeb webConfigService_by_id = webConfigService.find_by_id(1L);
        model.addAttribute("config", webConfigService_by_id);
        cacheManager.set("state_bind:" + state, 125, 120000);
        cacheManager.set("state_bind_openid:" + state, openid, 120000);
        model.addAttribute("openid", openid);
        return "bind_ok2";
    }


    /**
     * 绑定成功页面
     */
    @RequestMapping("/bind_ok2")
    public String bind_ok2(String state, Model model) {
        String openid;
        SystemWeb web = webConfigService.find_by_id(1L);
        model.addAttribute("config", web);
        openid = cacheManager.get("state_bind_openid:" + state);
        cacheManager.remove("state:" + state);
        model.addAttribute("openid", openid);
        cacheManager.remove("state_bind:" + state);
        return "bind_ok2";
    }

    /**
     * 绑定成功页面
     */
    @RequestMapping("/bind_ok")
    public String bind_ok(String state, Model model) throws Exception {
        Object o = cacheManager.get("state:" + state);
        Long id = (Long) o;
        if (id == null) {
            throw new Exception("用户识别失败!");
        }
        SystemUser user1 = userService.findUserById(id);
        model.addAttribute("user", user1);
        SystemWeb web = webConfigService.find_by_id(1L);
        model.addAttribute("config", web);
        cacheManager.remove("state:" + state);
        cacheManager.remove("state_bind:" + state);
        return "bind_ok";
    }

    /**
     * 忘记密码页面
     */
    @RequestMapping("/re_email")
    public String reset_pw(Model model) {
        SystemWeb web = webConfigService.find_by_id(1L);
        model.addAttribute("config", web);
        return "re_email";
    }

    /**
     * 重新发送账户信息
     */
    @RequestMapping("/re_email/send")
    @ResponseBody
    public Map send_email(String email) {
        HashMap<Object, Object> map = new HashMap<>();
        SmsConfig config = smsConfig.get_config(1L);
        SystemUser user = userService.find_user_by_email(email);
        if (user == null) {
            user = userService.findUserByPhone(email);
        }
        if (user == null) {
            map.put("msg", "账号不存在,请重新输入!");
            map.put("code", -1);
            return map;
        }
        SystemWeb web = webConfigService.find_by_id(1L);
        boolean mail = false;
        if (config.getNotifyType() == 0) {
            String con = "感谢您注册" + web.getSiteName() + "！<br>";
            con += "您的商户ID：" + user.getId() + " <br>";
            con += "您的商户秘钥：" + user.getAppkey() + "<br>";
            con += "您的登录用户名:" + user.getUser() + "<br>";
            con += "您的登录密码:" + user.getPwd() + "<br>";
            con += web.getSiteName() + "官网:" + web.getHttpUrl() + "<br>";
            con += "<a href=\" " + web.getHttpUrl() + "/admin/login \"> <br>";
            mail = mailUtils.sendMail(web.getSiteName() + "商户注册成功", con, user.getEmail(), web.getSiteName());
        } else {
            String con = "感谢您注册" + web.getSiteName() + ",";
            con += "用户名:" + user.getUser() + ",";
            con += "密码:" + user.getPwd() + ",";
            mail = SMSUtils.send_notify(config.getAppk2(), user.getPhone(), con, config.getAppSign());
        }
        if (mail) {
            map.put("msg", "账号密码已发送,请注意查收!");
            map.put("code", 0);
        } else {
            map.put("msg", "账号已找到但邮箱/电话错误,无法发送,请联系管理员处理!");
            map.put("code", -2);
        }
        return map;
    }

    /**
     * 文件上传
     */
    @RequestMapping("/upload")
    @ResponseBody
    public Map upload(MultipartFile picFile) throws Exception {
        HashMap<Object, Object> map = new HashMap<>();
        byte[] bytes = picFile.getBytes();
        String fileName = picFile.getOriginalFilename();
        if (StringUtils.isEmpty(fileName)) {
            throw new Exception("getOriginalFilename Error");
        }
        String extentionName = fileName.substring(fileName.lastIndexOf(".") + 1); // 后缀名
        String s = manager.saveFile(bytes, extentionName);
        map.put("msg", "上传完成!");
        map.put("code", 0);
        map.put("url", "/" + s);
        return map;
    }


}
